package serv

import (
	"erp/app"
	"erp/middleware"
	"erp/model"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"runtime/debug"
	"strconv"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
)

type FWebServer struct {
	gin.Context
}

func StartServer() {
	r := gin.Default()
	r.GET("/login.html", LoginCtrl)
	r.POST("/login.html", LoginCheckCtrl)

	clothesG := r.Group("/clothes")
	{
		clothesG.GET("/index.html", AuthCheck, ClothesIndexCtrl)
	}

	port := app.Config().Port

	r.Use(middleware.CrossSite)
	r.Use(middleware.NewMidLogger())
	r.Use(errorHttp)

	r.GET("/", IndexCtrl)

	r.Static("/static", "./public/static")
	r.Static("/assets", "./public/assets")
	r.StaticFile("/favicon.ico", "./static/favicon.ico")
	r.HTMLRender = loadTemplates("./templates")

	//记录pid
	ioutil.WriteFile("server.sock", []byte(fmt.Sprintf("%d,%d", os.Getppid(), os.Getpid())), 0666)

	r.Run(fmt.Sprintf(":%d", port))
}

func ApiErr(c *gin.Context, err error) {
	c.JSON(200, gin.H{"status": "err", "msg": err})
	log.Panicln(err)
}

// errorHttp 统一500错误处理函数
func errorHttp(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			//打印错误堆栈信息
			log.Printf("panic: %v\n", r)
			debug.PrintStack()
			//封装通用json返回
			c.HTML(200, "500.html", gin.H{
				"title": "500",
			})
		}
	}()
	c.Next()
}

// 模板载入函数
func loadTemplates(templatesDir string) multitemplate.Renderer {
	r := multitemplate.NewRenderer()

	bases, err := filepath.Glob(templatesDir + "/*.html")
	if err != nil {
		panic(err.Error())
	}

	includes, err := filepath.Glob(templatesDir + "/**/*.html")
	if err != nil {
		panic(err.Error())
	}

	for _, include := range includes {
		baseCopy := make([]string, len(bases))
		copy(baseCopy, bases)
		files := append(baseCopy, include)
		r.AddFromFiles(strings.Replace(include, "templates/", "", 1), files...)
	}

	return r
}

func AuthCheck(c *gin.Context) {
	token, _ := c.Cookie("token")
	// token := c.GetHeader("token")
	if token == "" {
		token = c.Query("token")
	}

	if token == "" {
		c.Redirect(302, "/login.html")
		c.Abort()
		return
	}

	// token = "1|1231235677777|123123"
	userinfo := ParseToken(token)
	if userinfo.Id == 0 {
		c.Redirect(302, "/login.html")
		// c.JSON(200, gin.H{
		// 	"code": 400,
		// 	"msg":  "验证失败",
		// })
		c.Abort()
		return
	}
	c.Set("userData", userinfo)
	// var expire int64 = 24 * 60 * 60
	// nowTime := time.Now().Unix()
	// if (nowTime - createTime) >= expire {
	// 	c.JSON(200, gin.H{
	// 		"code": 401,
	// 		"msg":  "token失效",
	// 	})
	// 	c.Abort()
	// }
}

func ParseToken(token string) model.User {
	token_arr := strings.Split(token, "|")

	userData := model.User{}

	if len(token_arr) == 3 {
		userId, _ := strconv.Atoi(token_arr[0])

		if userId > 0 {
			userData = userData.Get(userId)
		}
	} else {
		log.Println("没有取到客户度Token")
	}
	return userData
}
